﻿using System;
using System.Collections.Generic;
using System.Linq;
using BLToolkit.Data;
using Calendar.Logic.Core;
using Calendar.Logic.ObjectManager.Authorization;
using Calendar.Logic.ObjectModel;

namespace Calendar.Logic.ObjectManager
{
    internal static class EventManagerExtended
    {
    }

    public class EventManager : BaseManager<EventManager, Event>
    {
        public new Event SelectById(int id)
        {
            return Table.Where(e => e.ID == id).FirstOrDefault();
        }

        public List<Event> SelectAllByUserId(int userId)
        {
            var eventUser = EventUserManager.Table.Where(e => e.SCN_ID == userId && e.Author).Select(e=>e.FRS_ID).ToList();
            return Table.Where(eve => eventUser.Contains(eve.ID)).ToList();
        }

        public List<Event> SelectAllByUser(string username)
        {
            var userId = UserManager.Table.SelectByName(username).Select(u => u.ID).SingleOrDefault();
            return SelectAllByUserId(userId);
        }

        public List<Event> SelectAllFrendlyByUserId(int userId)
        {
            var eventUser = EventUserManager.Table.Where(e => e.SCN_ID == userId && !e.Author).Select(e => e.FRS_ID).ToList();
            return Table.Where(eve => eventUser.Contains(eve.ID)).ToList();
        }

        public List<Event> SelectAllFrendlyUser(string username)
        {
            var userId = UserManager.Table.SelectByName(username).Select(u => u.ID).SingleOrDefault();
            return SelectAllFrendlyByUserId(userId);
        }


        public Event CreateInstance(DateTime start, DateTime end, string title)
        {
            Event e = CreateInstance();
            e.Start = start;
            e.End = end;
            e.Title = title;
            return e;
        }

        public int CreateEvent(Event e)
        {
            return Insert(e);
        }

        public int RemoveEvent(int eventId)
        {
            try
            {
                return DeleteByKey(eventId);
            }
            catch (DataException)
            {
                throw new ManagerException("Данное событие используется в системе");
            }
        }

        public int Edit(Event ev)
        {
            return Update(ev);
        }

    }
}
